let { Api } = require('/utils/api.js');
let { NetWorkUtils } = require('/utils/network_util.js');
let { Utils } = require('/utils/utils.js');
let { Storage } = require('/utils/storage.js')
let baseInfo = require('/utils/base_info.js');
let network = null;
let api = null;
App({
  onLaunch: function () {
    //baseInfo.getBaseInfo(this);
    let that = this;
    network = new this.NetWorkUtils();
    api = new this.Api();

    /**
     * 1.如果有jsCode则直接获取openId，否从回调jsCodeReadyCallback中获取jsCode
     * 2.jsCode获取成功后，将jsCode设有全局变量（见回调openIdSuccess）
     * 3.获取jsCode后，通过jsCode获取openId
     * 4.通过openId获取商户信息，并将商户信息设有全局变量（见回调userAndTenantInfoSuccess）
     * 5.获取商户用户信息后，通过商户信息获取首页信息
     * 6.获取首页信息的同时会弹出授权对话，用户同意授权，则将微信用户信息上传到我们的服务器， 同时将用户信息设为全局变量
     */
    wx.login({
      success: function (res) {
        wx.showLoading()
        // 获取jsCode
        that.globalData.jsCode = res.code;
        if (wx.getExtConfig) {
          wx.getExtConfig({
            success: function (res) {
              console.log('----------jsCode----------')
              console.log(that.globalData.jsCode)
              // 获取appId
              that.globalData.appId = res.extConfig.appId;
              // 通过appId、jsCode到后台换取 openId, sessionKey, unionId
              wx.request({
                url: api.wxUrl,
                data: { appId: that.globalData.appId, jsCode: that.globalData.jsCode },
                success: function (res) {
                  console.log(res.data);
                  that.globalData.openId = res.data.data.openid;
                  that.globalData.sessionKey = res.data.data.session_key;
                  // 获取用户及商户信息
                  wx.request({
                    url: api.getUserInfo,
                    data: { appId: that.globalData.appId, openId: that.globalData.openId },
                    method: 'POST',
                    success: function (res) {
                      wx.hideLoading();
                      console.log(res.data.data)
                      if (res.data.data) {
                        let userAndTenantInfo = res.data.data;
                        if (userAndTenantInfo.mobile) {
                          console.log(userAndTenantInfo.mobile);
                        } else {
                          userAndTenantInfo.mobile = '';
                        }
                        that.globalData.userAndTenantInfo = userAndTenantInfo;
                        that.globalData.userId = userAndTenantInfo.id;
                        that.globalData.tenantId = userAndTenantInfo.tenantId;
                        if (that.userAndTenantInfoCallback) {
                          that.userAndTenantInfoCallback(userAndTenantInfo)
                        }
                      }
                    },
                    fail: function (res) {
                      network._error(api.wxError, res);
                    }
                  })
                },
                fail: function (res) {
                  network._error(api.wxError, res);
                }
              })
            }
          })
        }
        // 获取用户信息
        wx.getSetting({
          success(res) {
            if (!res.authSetting['scope.userInfo']) {
              // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
              wx.getUserInfo({
                success: function (res) {
                  // 可以将 res 发送给后台解码出 unionId
                  console.log(res)
                  that.globalData.userInfo = res.userInfo
                  // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                  // 所以此处加入 callback 以防止这种情况
                  if (that.userInfoReadyCallback) {
                    that.userInfoReadyCallback(res)
                  }
                  
                  network._post_json(that, api.modifyUserInfo, { nickName: res.userInfo.nickName, avatarUrl: res.userInfo.avatarUrl, gender: that.globalData.userInfo.gender }, modifySuccess);
                }
              })
            }
          }
        })
      },
    })
  },
  // 公共变量
  globalData: {
    userInfo: null,
    jsCode: null,
    appId: null,
    openId: null,
    sessionKey: null,
    userId: null,
    tenantId: null,
    userAndTenantInfo: null,
    storeId: null,
    timeStamp: 0
  },
  linkId: null,
  NetWorkUtils,
  Api,
  Utils,
  Storage: Storage
})

var modifySuccess = function (that, res) {

}
